//
//  ConnactCell.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/20.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import RxSwift
import YBImageBrowser
import RxCocoa

class ConnactCell: UITableViewCell {

    let itemHeight = (SCREEN_WIDTH - 60) / 3 - 1
    
    let timeLabel = UILabel()
    let editButton = UIButton()
    let contentLabel = UILabel()
    let numberLabel = UILabel()
    var collectionView: UICollectionView!
    let repeatContentView = UIView()
    let repeatLabel = UILabel()
    let imageArray = BehaviorRelay<[String]>.init(value: [])
    var clickDetailClosure: () -> () = {}
    var clickDelete: () -> () = {}
    var clickEdit: () -> () = {}
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        self.backgroundColor = .clear
        
        let contentView = UIView().config
            .backgroundColor(.white)
            .addTo(self)
            .makeConstraints { (make) in
                make.left.top.right.equalToSuperview()
                make.bottom.equalTo(-15)
            }.view
        
        timeLabel.config
            .font(UIFont.systemFont(ofSize: 12, weight: .medium))
            .textColor(#colorLiteral(red: 0.6901960784, green: 0.6901960784, blue: 0.6901960784, alpha: 1))
            .addTo(contentView)
            .makeConstraints { (make) in
                make.left.equalTo(15)
                make.top.equalTo(15)
        }
        
        let deleteButton = UIButton()
            .config
            .image(UIImage.init(named: "fake_delete"))
            .addTarget(self, action: #selector(deleteButtonClick))
            .addTo(contentView)
            .makeConstraints { (make) in
                make.right.equalTo(-10)
                make.height.width.equalTo(30)
                make.centerY.equalTo(timeLabel.snp.centerY)
        }.view
        
        editButton
            .config
            .image(UIImage.init(named: "fake_edit"))
            .addTarget(self, action: #selector(editButtonClick))
            .addTo(contentView)
            .makeConstraints { (make) in
                make.right.equalTo(deleteButton.snp.left)
                make.height.width.equalTo(30)
                make.centerY.equalTo(timeLabel.snp.centerY)
        }
        
        contentLabel.config
            .font(UIFont.systemFont(ofSize: 14, weight: .medium))
            .textColor(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1))
            .numberOfLines(0)
            .addTo(contentView)
            .makeConstraints { (make) in
                make.left.equalTo(15)
                make.top.equalTo(timeLabel.snp.bottom).offset(15)
                make.right.equalTo(-10)
        }
        
        numberLabel.config
            .font(UIFont.systemFont(ofSize: 12, weight: .medium))
            .textColor(APPConfig.baseColor)
            .numberOfLines(0)
            .addTo(contentView)
            .makeConstraints { (make) in
                make.top.equalTo(contentLabel.snp.bottom).offset(15)
                make.left.equalTo(40)
                make.right.equalTo(-15)
        }
        
        UIImageView().config
            .image(#imageLiteral(resourceName: "connact_icon"))
            .addTo(contentView)
            .makeConstraints { (make) in
                make.left.equalTo(15)
                make.height.equalTo(5)
                make.width.equalTo(19)
                make.centerY.equalTo(numberLabel.snp.centerY)
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets.init(top: 15, left: 15, bottom: 0, right: 15)
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.itemSize = CGSize(width: itemHeight, height: itemHeight)
        
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
            .config
            .backgroundColor(.white)
            .register(ConnactItemCell.self)
            .addTo(contentView)
            .makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(numberLabel.snp.bottom)
                make.height.equalTo(0)
                make.bottom.equalTo(-15)
            }.view
        
        repeatLabel.config
            .numberOfLines(2)
            .font(UIFont.systemFont(ofSize: 14, weight: .medium))
            .textColor(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1))
        
        repeatContentView.config
            .backgroundColor(#colorLiteral(red: 0.9528377652, green: 0.9530007243, blue: 0.9528275132, alpha: 1))
            .cornerRadius(5)
            .isUserInteractionEnabled(true)
            .addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(showDetail)))
            .addTo(contentView)
            .makeConstraints { (make) in
                make.left.equalTo(15)
                make.right.equalTo(-15)
                make.top.equalTo(collectionView.snp.bottom).offset(15)
                make.height.equalTo(repeatLabel.font.lineHeight * 2 + 25)
        }
        
        repeatLabel.config
            .addTo(repeatContentView)
            .makeConstraints { (make) in
                make.left.top.equalTo(10)
                make.right.equalTo(-10)
        }
        
        UIButton().config
            .backgroundColor(APPConfig.baseColor)
            .cornerRadius(3)
            .titleColor(.white)
            .isUserInteractionEnabled(false)
            .font(.systemFont(ofSize: 10, weight: .medium))
            .title("详情".localized)
            .addTo(repeatContentView)
            .makeConstraints { (make) in
                make.height.equalTo(16)
                make.bottom.equalTo(-10)
                make.right.equalTo(-10)
                make.width.equalTo(40)
        }
        
        imageArray
            .bind(to: collectionView.rx.items(cellType: ConnactItemCell.self)) { (_, id, cell) in
                cell.imageView.sd_setImage(with: URL.init(string: APPConfig.imagePath + id), placeholderImage: UIImage.init(named: "placeholder_image"), options: .retryFailed, context: nil)
            }.disposed(by: rx.disposeBag)
        
        collectionView.rx.itemSelected
            .subscribe(onNext: { (index) in
                let browser = YBImageBrowser.init()
                browser.toolViewHandlers = []
                browser.dataSource = self
                browser.currentPage = index.item
                browser.show()
            }).disposed(by: rx.disposeBag)
    }
    
    @objc func editButtonClick() {
        clickEdit()
    }
    
    @objc func deleteButtonClick() {
        clickDelete()
    }
    
    @objc func showDetail() {
        clickDetailClosure()
    }
    
    func bind(_ model: ConnactModel) {
        timeLabel.text = model.createTime
        imageArray.accept(model.ossList.map{ $0.id })
        
        let attr = NSMutableAttributedString.init(string: model.content)
        attr.setParagraphSpace(5)
        contentLabel.attributedText = attr
        numberLabel.text = model.number
        
        let lines = model.ossList.count % 3 == 0 ? model.ossList.count / 3 : model.ossList.count / 3 + 1
        collectionView.isHidden = model.ossList.count == 0
        collectionView.snp.updateConstraints { (make) in
            make.height.equalTo((itemHeight + 15) * CGFloat(lines))
        }
        
        let replyContent = model.replyContent[0..<Int(SCREEN_WIDTH / (model.replyContent.hasChinese ? 11: 6))] + "..."
        
        let attr2 = NSMutableAttributedString.init(string: replyContent)
        attr2.setParagraphSpace(5)
        repeatLabel.attributedText = attr2
        
        repeatContentView.isHidden = model.replyContent.count == 0
        
        let collectionViewBottonMargon = model.replyContent.count == 0 ? 0 : ((repeatLabel.font.lineHeight * 2 + 25) + 15)
        collectionView.snp.updateConstraints { (make) in
            make.bottom.equalTo(-15 - collectionViewBottonMargon)
        }
        editButton.isHidden = model.isComplete == 1
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension ConnactCell: YBImageBrowserDataSource {
    
    func yb_numberOfCells(in imageBrowser: YBImageBrowser) -> Int {
        return self.imageArray.value.count
    }
    
    func yb_imageBrowser(_ imageBrowser: YBImageBrowser, dataForCellAt index: Int) -> YBIBDataProtocol {
        let cell = collectionView.cellForItem(at: IndexPath.init(item: Int(index), section: 0)) as? ConnactItemCell
        let data = YBIBImageData()
        data.imageURL = URL.init(string: APPConfig.imagePath + self.imageArray.value[index])
        data.projectiveView = cell?.imageView
        return data
    }
    
}

class ConnactItemCell: UICollectionViewCell {
    
    let imageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView.config
            .backgroundColor(.lightGray)
            .contentMode(.scaleAspectFill)
            .clipsToBounds(true)
            .addTo(self)
            .makeConstraints { (make) in
                make.edges.equalToSuperview()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
